using System;
using System.Linq;
using RomanJendrusz.Amazon.ETL.Domain;
using RomanJendrusz.Amazon.ETL.Infrastructure.DataBase;

namespace RomanJendrusz.Amazon.ETL.Repositories
{
    public class CustomerReviewsRepository: Repository<CustomerReview, int>, ICustomerReviewRepository
    {
        private readonly ICustomerRepository customerRepository;

        public CustomerReviewsRepository(ISession session, ICustomerRepository customerRepository)
            : base(session, s => s.CustomersReviews, "CustomerReviewId")
        {
            this.customerRepository = customerRepository;
        }

        public CustomerReview AttachIfAllreadyExists(CustomerReview item)
        {
            if(item == null)
            {
                return null;
            }
            CustomerReview persistedReview;
            if(item.Customer == null || item.Customer.CustomerId == null)
            {
                persistedReview = session.CustomersReviews.FirstOrDefault(
                r => r.AddedDate == item.AddedDate && r.Book == item.Book
                    && r.Customer == null && item.Summary == r.Summary);
            }
            else
            {
                persistedReview = session.CustomersReviews.FirstOrDefault(
                r => r.AddedDate == item.AddedDate && r.Book == item.Book
                    && r.Customer == item.Customer && item.Summary == r.Summary);
            }
            if(persistedReview != null)
            {
                clone(item, persistedReview);
                return persistedReview;
            }
            item.Customer = customerRepository.AttachIfAllreadyExists(item.Customer);
            return item;
        }

        public void clone(CustomerReview attached, CustomerReview orginal)
        {
            orginal.Content = attached.Content;
            orginal.HelpfulVotes = attached.HelpfulVotes;
            orginal.Rating = attached.Rating;
            orginal.Summary = attached.Summary;
            orginal.TotalVotes = attached.TotalVotes;
        }
    }
}